package com.spdb.spdbfl.database;

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataSource {
    private static HashMap<String, DruidDataSource> dataSourceMap = new HashMap();

    public DataSource() {
    }

    private static void init(String connectString) {
        if (dataSourceMap.get(connectString) == null) {
            DruidDataSource dataSource = new DruidDataSource();
            if (connectString.toLowerCase().indexOf("postgresql") > 0) {
                dataSource.setDriverClassName("org.postgresql.Driver");
            } else {
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            }

            if (connectString.indexOf("useSSL") == -1) {
                dataSource.setUrl(connectString + "&useSSL=false");
            } else {
                dataSource.setUrl(connectString);
            }

            dataSource.setInitialSize(5);
            dataSource.setMinIdle(1);
            dataSource.setMaxActive(20);
            dataSourceMap.put(connectString, dataSource);
        }

    }

    public static Connection getConnection(String connectString){
        if(dataSourceMap.get(connectString)==null){
            init(connectString);
        }
        try{
            return ((DruidDataSource)dataSourceMap.get(connectString)).getConnection();
        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String conn = "jdbc:mysql://10.116.2.244:3306/puyin?user=puyin&password=Jason71419831224Wb";
        String sql = "select * from puyin.lease_assets limit 10;";
        List<Map<String, Object>> listMap = DBOperate.select(conn, sql);
        System.out.println("count=" + listMap.size());
    }

}
